import React, { useState, useEffect, useCallback } from 'react';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, KeyOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, Input, Space, Table, Pagination, Modal, message, Tag, Typography } from 'antd';
import type { GetProps, TableProps } from 'antd';
import type { IRoles } from '../types/role';
import { Add } from './add';
import { EditRole } from './edit';
import http from '../api/http';
import { RoleAuthModal } from './auth';

// 样式变量统一管理
const COLORS = {
  primary: '#1890ff',       // 主色-编辑
  auth: '#52c41a',          // 授权-绿色
  delete: '#ff4d4f',        // 删除-红色
  add: '#1890ff',           // 添加-主色
  btnRadius: '6px',         // 按钮圆角
  btnPadding: '0 14px',     // 按钮内边距
  btnHeight: '32px',        // 操作按钮高度
  searchHeight: '34px',     // 搜索框高度
  addBtnHeight: '34px'      // 添加按钮高度
};

interface PaginationParams {
  current: number; // 当前页码
  pageSize: number; // 每页条数
  total: number; // 总条数
}

export default function Roles() {
  type SearchProps = GetProps<typeof Input.Search>;
  const { Search } = Input;
  const { Text } = Typography;
  const [data, setData] = useState<Array<IRoles>>([]);
  
  // 分页状态
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  
  const [name, setName] = useState('');

  // 获取角色列表数据
  const search = useCallback(() => {
    http.getList<IRoles>('Roles/page', { 
      name: name, 
      page: pagination.current, 
      size: pagination.pageSize 
    }).then(res => {
      setData(res.data);
      setPagination(prev => ({
        ...prev,
        total: res.count,
        current: res.page || prev.current
      }));
    }).catch(err => {
      console.error(err);
    });
  }, [pagination.current, pagination.pageSize, name]);

  useEffect(() => {
    search();
  }, [name, search]);

  // 分页变化处理
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination({
      current: page,
      pageSize,
      total: pagination.total,
    });
  };

  // 搜索处理
  const onSearch: SearchProps['onSearch'] = (value) => {
    setName(value);
  };

  // 刷新列表数据
  const refreshRoles = () => {
    search();
  };

  // 添加角色相关状态与方法
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 编辑角色相关状态与方法
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentEditData, setCurrentEditData] = useState<IRoles | null>(null);
  const handleEdit = (data: IRoles) => {
    setIsEditModalOpen(true);
    setCurrentEditData(data);
  };

  // 授权弹窗相关状态与方法
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);
  const [currentAuthRoleId, setCurrentAuthRoleId] = useState(0);
  const handleOpenAuthModal = (roleId: number) => {
    setCurrentAuthRoleId(roleId);
    setIsAuthModalOpen(true);
  };
  const handleAuthSuccess = () => {
    message.info('角色权限已更新');
  };

  // 单个删除
  const handleDelete = (roleId: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？删除后不可恢复',
      icon: <ExclamationCircleOutlined style={{ color: COLORS.delete }} />,
      okText: '确认删除',
      cancelText: '取消',
      okButtonProps: {
        style: { 
          backgroundColor: COLORS.delete, 
          borderColor: COLORS.delete,
          borderRadius: COLORS.btnRadius,
          padding: COLORS.btnPadding,
          height: COLORS.btnHeight
        }
      },
      cancelButtonProps: {
        style: { 
          borderRadius: COLORS.btnRadius,
          padding: COLORS.btnPadding,
          height: COLORS.btnHeight
        }
      },
      onOk: async () => {
        try {
          await http.delete('Roles',{id:roleId});
          message.success('删除成功');
          search();
        } catch (err) {
          message.error('删除失败');
          console.error(err);
        }
      },
    });
  };

  // 表格列配置（核心优化：描述字段缩短至8字）
  const columns: TableProps<IRoles>['columns'] = [
    {
      title: '角色ID',
      dataIndex: 'roleId',
      key: 'roleId',
      width: 80,
      align: 'center',
      render: (text) => <Text type="secondary">{text}</Text>
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      width: 160,
      align: 'center',
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '所属部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 160,
      align: 'center',
      render: (text) => (
        <Tag 
          color={COLORS.auth} 
          size="small"
          style={{ borderRadius: '4px', padding: '2px 8px' }}
        >
          {text}
        </Tag>
      )
    },
    {
      title: '角色描述',
      dataIndex: 'remark',
      key: 'remark',
      width: 140, // 限制列宽，配合短描述
      align: 'center',
      // 核心优化：描述缩短至8字，超出部分省略
      render: (text) => {
        if (!text) {
          return <Text type="secondary" italic>无</Text>; // 简洁空描述
        }
        // 只显示前8个字，超出部分用...代替
        return text.length > 8 ? (
          <Text 
            tooltip={{ 
              title: text,
              placement: 'top',
              mouseEnterDelay: 0.3 // 延迟显示tooltip，避免误触
            }}
          >
            {text.slice(0, 8)}...
          </Text>
        ) : (
          text
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      align: 'center',
      render: (_: any, record: IRoles) => (
        <Space size="small">
          {/* 编辑按钮 */}
          <Button
            icon={<EditOutlined />}
            size="small"
            onClick={() => handleEdit(record)}
            style={{ 
              backgroundColor: COLORS.primary,
              borderColor: COLORS.primary,
              color: '#fff',
              borderRadius: COLORS.btnRadius,
              padding: COLORS.btnPadding,
              height: COLORS.btnHeight,
              fontSize: '13px'
            }}
          >
            编辑
          </Button>

          {/* 授权按钮 */}
          <Button
            icon={<KeyOutlined />}
            size="small"
            onClick={() => handleOpenAuthModal(record.roleId)}
            style={{ 
              backgroundColor: COLORS.auth,
              borderColor: COLORS.auth,
              color: '#fff',
              borderRadius: COLORS.btnRadius,
              padding: COLORS.btnPadding,
              height: COLORS.btnHeight,
              fontSize: '13px'
            }}
          >
            授权
          </Button>

          {/* 删除按钮 */}
          <Button
            icon={<DeleteOutlined />}
            size="small"
            onClick={() => handleDelete(record.roleId)}
            style={{ 
              backgroundColor: COLORS.delete,
              borderColor: COLORS.delete,
              color: '#fff',
              borderRadius: COLORS.btnRadius,
              padding: COLORS.btnPadding,
              height: COLORS.btnHeight,
              fontSize: '13px'
            }}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      {/* 搜索和添加按钮区域 */}
      <div style={{ 
        marginBottom: '20px', 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        gap: '12px'
      }}>
        <Search 
          placeholder="输入角色名称搜索" 
          onSearch={onSearch} 
          style={{ 
            width: '220px',
            height: COLORS.searchHeight,
            borderRadius: `${COLORS.btnRadius} 0 0 ${COLORS.btnRadius}`
          }}
          allowClear
          enterButton={
            <Button 
              type="primary" 
              icon={<SearchOutlined />}
              size="middle"
              style={{ 
                backgroundColor: COLORS.primary,
                borderColor: COLORS.primary,
                borderRadius: `0 ${COLORS.btnRadius} ${COLORS.btnRadius} 0`,
                height: COLORS.searchHeight,
                padding: '0 14px',
                fontSize: '13px'
              }}
            >
              搜索
            </Button>
          }
        />

        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showModal}
          size="middle"
          style={{ 
            backgroundColor: COLORS.add,
            borderColor: COLORS.add,
            borderRadius: COLORS.btnRadius,
            padding: '0 18px',
            height: COLORS.addBtnHeight,
            fontSize: '13px',
            boxShadow: '0 2px 6px rgba(24, 144, 255, 0.2)',
            transition: 'all 0.3s ease'
          }}
        >
          添加角色
        </Button>
      </div>

      {/* 表格区域 */}
      <Table
        dataSource={data}
        columns={columns}
        rowKey="roleId"
        bordered
        pagination={false}
        locale={{ emptyText: '暂无角色数据' }}
        style={{ 
          borderRadius: COLORS.btnRadius,
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
          marginBottom: '20px'
        }}
        // 空数据展示
        emptyText={
          <div style={{ 
            textAlign: 'center', 
            padding: '40px 0',
            backgroundColor: 'rgba(0,0,0,0.02)',
            borderRadius: '12px'
          }}>
            <div style={{ color: '#9ca3af', fontSize: '16px', marginBottom: '12px' }}>暂无角色数据</div>
            <Button 
              type="text" 
              icon={<PlusOutlined />}
              onClick={showModal}
              style={{ color: COLORS.primary }}
            >
              点击添加第一个角色
            </Button>
          </div>
        }
      />

      {/* 分页区域 */}
      {pagination.total > 0 && (
        <div style={{ textAlign: 'center', marginTop: '10px' }}>
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条数据`}
            pageSizeOptions={['10', '20', '50']}
            onChange={handlePaginationChange}
            onShowSizeChange={(current, size) => handlePaginationChange(current, size)}
            style={{ fontSize: '13px' }}
            itemStyle={{ borderRadius: COLORS.btnRadius }}
            pageItemStyle={{ borderRadius: COLORS.btnRadius }}
            prevIconStyle={{ borderRadius: COLORS.btnRadius }}
            nextIconStyle={{ borderRadius: COLORS.btnRadius }}
            jumpNextIconStyle={{ borderRadius: COLORS.btnRadius }}
            jumpPrevIconStyle={{ borderRadius: COLORS.btnRadius }}
          />
        </div>
      )}

      {/* 弹窗组件 */}
      <Add 
        isModalOpen={isModalOpen} 
        handleCancel={handleCancel} 
        handleOk={handleOk}
        onSuccess={refreshRoles}
      />
      
      <EditRole 
        isModalOpen={isEditModalOpen}
        editData={currentEditData}
        handleCancel={() => setIsEditModalOpen(false)}
        onSuccess={refreshRoles}
      />
      
      <RoleAuthModal
        isOpen={isAuthModalOpen}
        roleId={currentAuthRoleId}
        onClose={() => setIsAuthModalOpen(false)}
        onSuccess={handleAuthSuccess}
      />
    </div>
  );
}